<?php
class Ueditor_model extends Base_Model
{
    private $_resource_url;
    private $_list_dir;
    private $_list_url;
    public function __construct()
    {
        parent::__construct();
        $this->_list_dir = "/home/nldou/webroot/wap";
        $this->_list_url = "http://wap.nldou.com";
    }
    
    public function upload($action,$config)
    {
        $base64 = "upload";
        switch ($action) {
            case 'catchimage':
                $upconfig = array(
                    "pathFormat" => $config['catcherPathFormat'],
                    "maxSize" => $config['catcherMaxSize'],
                    "allowFiles" => $config['catcherAllowFiles'],
                    "sourceType" => 'catchimage'
                );
                $fieldName = $config['catcherFieldName'];
                break;
            case 'uploadimage':
                $upconfig = array(
                    "pathFormat" => $config['imagePathFormat'],
                    "maxSize" => $config['imageMaxSize'],
                    "allowFiles" => $config['imageAllowFiles'],
                    "sourceType" => 'image' 
                );
                $fieldName = $config['imageFieldName'];
                break;
            case 'uploadscrawl':
                $upconfig = array(
                    "pathFormat" => $config['scrawlPathFormat'],
                    "maxSize" => $config['scrawlMaxSize'],
                    "allowFiles" => $config['scrawlAllowFiles'],
                    "oriName" => "scrawl.png",
                    "sourceType" => 'scrawl'
                );
                $fieldName = $config['scrawlFieldName'];
                $base64 = "base64";
                break;
            case 'uploadvideo':
                $upconfig = array(
                    "pathFormat" => $config['videoPathFormat'],
                    "maxSize" => $config['videoMaxSize'],
                    "allowFiles" => $config['videoAllowFiles'],
                    "sourceType" => 'video'
                );
                $fieldName = $config['videoFieldName'];
                break;
            case 'uploadfile':
            default:
                $upconfig = array(
                    "pathFormat" => $config['filePathFormat'],
                    "maxSize" => $config['fileMaxSize'],
                    "allowFiles" => $config['fileAllowFiles'],
                    "sourceType" => 'file'
                );
                $fieldName = $config['fileFieldName'];
                break;
        }

        switch ($upconfig['sourceType']){
            case 'image':
                $this->_resource_url = "http://wap.nldou.com";
                break;
            case 'video':
                $this->_resource_url = "http://media.nldou.com";
                break;
            case 'file':
                $this->_resource_url = "http://wap.nldou.com";
                break;
            case 'scrawl':
                $this->_resource_url = "http://wap.nldou.com";
                break;
            case 'catchimage':
                $this->_resource_url = "http://wap.nldou.com";
                break;
        }

        /* 生成上传实例对象并完成上传 */
        if ($upconfig['sourceType']==='catchimage'){
            $catchlist=array();
            if (isset($_POST[$fieldName])) {
                $catchsource = $_POST[$fieldName];
            } else {
                $catchsource = $_GET[$fieldName];
            }
            //远程抓取列表
            foreach ($catchsource as $imgUrl) {
                $initdata=array('fileField'=>$fieldName,'config'=>$upconfig,'type'=>"remote");
                $this->load->library('ueditor/Uploader',$initdata);
                $res = $this->uploader->getFileInfo();
                //处理图片
                if (isset($config['catcherWidth'])&&isset($config['catcherMasterDim'])&&isset($config['catcherMaintain'])&&$res['type']!='.gif'){
                    $imgproc['source_image'] = $res['url'];
                    $imgproc['width']     = $config['imageWidth'];
                    $imgproc['maintain_ratio'] = $config['imageMaintain'];
                    $imgproc['master_dim'] = $config['imageMasterDim'];
                    $this->load->library('image_lib', $imgproc);
                    $this->image_lib->resize();
                    $this->image_lib->clear();
                }
                array_push($catchlist, array(
                    "state" => $res["state"],
                    "url" => $this->_resource_url.$res['fullname'],
                    "size" => $res["size"],
                    "title" => htmlspecialchars($res["title"]),
                    "original" => htmlspecialchars($res["original"]),
                    "source" => htmlspecialchars($imgUrl)
                ));
            }
            /* 返回抓取数据 */
            return json_encode(array(
                'state'=> count($catchlist) ? 'SUCCESS':'ERROR',
                'list'=> $catchlist
            ));
        }else{
            $initdata=array('fileField'=>$fieldName,'config'=>$upconfig,'type'=>$base64);
            $this->load->library('ueditor/Uploader',$initdata);

            /* 返回数据 */
            $res = $this->uploader->getFileInfo();
            /* 处理图片 */
            if ($upconfig['sourceType']=='image'&&isset($config['imageWidth'])
                &&isset($config['imageMasterDim'])&&isset($config['imageMaintain'])&&$res['type']!='.gif'){
                $imgproc['source_image'] = $res['url'];
                $imgproc['width']     = $config['imageWidth'];
                $imgproc['maintain_ratio'] = $config['imageMaintain'];
                $imgproc['master_dim'] = $config['imageMasterDim'];
                $this->load->library('image_lib', $imgproc);
                $this->image_lib->resize();
                $this->image_lib->clear();
            }
            $res['url'] = $this->_resource_url.$res['fullname'];

            return json_encode($res);
        }
    }
    
    public function getlist($action,$config,$size,$start)
    {
        /* 判断类型 */
        switch ($action) {
            /* 列出文件 */
            case 'listfile':
                $allowFiles = $config['fileManagerAllowFiles'];
                $listSize = $config['fileManagerListSize'];
                $path = $config['fileManagerListPath'];
                break;
            /* 列出图片 */
            case 'listimage':
            default:
                $allowFiles = $config['imageManagerAllowFiles'];
                $listSize = $config['imageManagerListSize'];
                $path = $config['imageManagerListPath'];
        }
        $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);

        /* 获取参数 */
        $size = isset($size) ? htmlspecialchars($_GET['size']) : $listSize;
        $start = isset($start) ? htmlspecialchars($_GET['start']) : 0;
        $end = $start + $size;

        /* 获取文件列表 */
        $path = $this->_list_dir . (substr($path, 0, 1) == "/" ? "":"/") . $path;
        $files = $this->getfiles($path, $allowFiles);

        if (!count($files)) {
            return json_encode(array(
                "state" => "no match file",
                "list" => array(),
                "start" => $start,
                "total" => count($files)
            ));
        }

        /* 获取指定范围的列表 */
        $len = count($files);
//        for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){
//            $list[] = $files[$i];
//        }
        //时间最新优先排序
        $ftimes = array();
        foreach ($files as $f){
            $ftimes[] = $f['mtime'];
        }
        array_multisort($ftimes,SORT_DESC,$files);

        for ($i = $start, $list = array(); $i < $len && $i < min($end,$len)-1; $i++){
            $list[] = $files[$i];
        }

        /* 返回数据 */
        $result = json_encode(array(
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => count($files)
        ));

        return $result;



    }
    /**
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param array $files
     * @return array
     */
    public function getfiles($path, $allowFiles, &$files = array())
    {
        if (!is_dir($path)) return null;
        if(substr($path, strlen($path) - 1) != '/') $path .= '/';
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                //只打开YYYYMMDD格式的目录
                if (is_dir($path2)
                    && preg_match("/\d{4}\d{2}\d{2}/",substr($path2, strlen($this->_list_dir."/upload/images/")))) {
                    $this->getfiles($path2, $allowFiles, $files);
                } else {
                    if (preg_match("/\.(".$allowFiles.")$/i", $file)) {
                        $files[] = array(
                            'url'=> $this->_list_url.substr($path2, strlen($this->_list_dir)),
                            'mtime'=> filemtime($path2)
                        );
                    }
                }
            }
        }
        return $files;
    }

}